package com.database.service.impl;


import com.database.character.Attention;
import com.database.character.UserAccount;
import com.database.mapper.AttentionMapper;
import com.database.mapper.UserMapper;
import com.database.service.AttentionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class AttentionServiceImpl implements AttentionService {

  @Autowired
  private AttentionMapper attentionMapper;

  @Autowired
  private UserMapper userMapper;

  @Override
  public int addAttention(Attention attention) {
    Integer userId = attention.getUserId();
    Integer focusedId = attention.getFocusedId();
    UserAccount userAccount1 = userMapper.getByUid(userId);
    UserAccount userAccount2 = userMapper.getByUid(focusedId);
    userAccount1.setAttentionNum(userAccount1.getAttentionNum() + 1);//用户1关注数加一
    userAccount2.setAttentionNum(userAccount2.getFocusedNum() + 1);//用户2被关注数加一
    userAccount1.setUpdateTime(LocalDateTime.now());//用户1更新时间
    userAccount2.setUpdateTime(LocalDateTime.now());//用户2更新时间
    userMapper.updateUser(userAccount1);
    userMapper.updateUser(userAccount2);
    return attentionMapper.addAttention(attention);
  }

  @Override
  public int deleteAttentionByFocusedId(Integer focusedId) {
    UserAccount userAccount1 = userMapper.getByUid(focusedId);
    userAccount1.setAttentionNum(userAccount1.getFocusedNum() - 1);//用户1被关注数减一
    userAccount1.setUpdateTime(LocalDateTime.now());//用户1更新时间
    userMapper.updateUser(userAccount1);
    Attention attention = attentionMapper.getAttentionByFocusedId(focusedId);
    Integer userId = attention.getUserId();
    UserAccount userAccount2 = userMapper.getByUid(userId);
    userAccount2.setAttentionNum(userAccount2.getAttentionNum() - 1);//用户2关注数减一
    userAccount2.setUpdateTime(LocalDateTime.now());//用户2更新时间
    userMapper.updateUser(userAccount2);
    return attentionMapper.deleteAttentionByFocusedId(focusedId);
  }

  @Override
  public List<Attention> getAttentionByUid(Integer userId) {
    return attentionMapper.getAttentionByUid(userId);
  }
}
